"""
TTS工厂类
负责创建和管理TTS实现类的实例
"""

from typing import Dict, Type
import importlib
import logging
import sys
import os

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

# 导入TTS实现基类
from .implementations.base import TTSImplementation
# 导入配置
from config import TTS_IMPLEMENTATION


class TTSFactory:
    """
    TTS实现类的工厂类
    根据配置创建对应的TTS实现实例
    """
    
    # 实现类映射字典
    _implementations: Dict[str, Type[TTSImplementation]] = {}
    
    @classmethod
    def register_implementation(cls, name: str, implementation_class: Type[TTSImplementation]):
        """
        注册TTS实现类
        
        Args:
            name: 实现类名称
            implementation_class: 实现类类型
        """
        # 将实现类注册到映射字典中
        cls._implementations[name] = implementation_class
        logging.info(f"已注册TTS实现: {name}")
    
    @classmethod
    def create_implementation(cls, implementation_name: str = None) -> TTSImplementation:
        """
        创建TTS实现实例
        
        Args:
            implementation_name: 实现类名称，如果为None则使用配置文件中的默认值
            
        Returns:
            TTSImplementation: TTS实现实例
            
        Raises:
            ValueError: 当指定的实现类不存在时
        """
        # 使用配置文件中的默认值
        if implementation_name is None:
            implementation_name = TTS_IMPLEMENTATION
        
        # 如果尚未注册实现类，尝试动态加载
        if implementation_name not in cls._implementations:
            cls._load_implementation(implementation_name)
        
        # 检查实现类是否存在
        if implementation_name not in cls._implementations:
            available = list(cls._implementations.keys())
            raise ValueError(
                f"TTS实现 '{implementation_name}' 不存在。可用实现: {available}"
            )
        
        # 创建实例
        implementation_class = cls._implementations[implementation_name]
        return implementation_class()
    
    @classmethod
    def _load_implementation(cls, implementation_name: str):
        """
        动态加载实现类
        
        Args:
            implementation_name: 实现类名称
        """
        try:
            # 根据实现类名称构建模块路径
            module_name = f"src.tts.implementations.{implementation_name}_impl"
            # 动态导入模块
            module = importlib.import_module(module_name)
            
            # 构建类名（首字母大写 + Implementation）
            class_name = f"{implementation_name.capitalize()}Implementation"
            
            # 获取实现类
            implementation_class = getattr(module, class_name)
            
            # 注册实现类
            cls.register_implementation(implementation_name, implementation_class)
            
        except (ImportError, AttributeError) as e:
            logging.warning(f"加载TTS实现 '{implementation_name}' 失败: {e}")
    
    @classmethod
    def get_available_implementations(cls) -> Dict[str, str]:
        """
        获取所有可用的实现类信息
        
        Returns:
            Dict[str, str]: 实现类名称到描述的映射
        """
        # 确保默认实现已加载
        cls._load_implementation(TTS_IMPLEMENTATION)
        
        # 返回所有已注册实现的描述信息
        return {
            name: impl_class.__doc__ or "无描述"
            for name, impl_class in cls._implementations.items()
        }


# 注册内置实现类
TTSFactory.register_implementation('edge_tts', 
    __import__('src.tts.implementations.edge_tts_impl', fromlist=['EdgeTTSImplementation']).EdgeTTSImplementation)